<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { axiosrmedical } from '../../http/axiosRead';

const router = useRouter();

// 定义数据结构接口
interface PaymentItem {
  id: number;
  itemName: string;
  departmentName: string;
  doctorName: string;
  amount: number;
  createdTime: string;
}

interface PatientData {
  patientId: number;
  patientName: string;
  idCard: string;
  phoneNumber: string;
  cardBalance: number;
  paymentItems: PaymentItem[];
  relation?: string; // 添加与患者的关系
}

interface ResponseData {
  msg: string;
  code: number;
  data: PatientData;
}

// 患者接口
interface Patient {
  id: number;
  name: string;
  idCard: string;
  relation: string;
}

interface PatientResponse {
  msg: string;
  code: number;
  totaCount: number;
  totaPage: number;
  pageData: Patient[];
}

// 响应数据
const patientData = ref<PatientData>({
  patientId: 0,
  patientName: '',
  idCard: '',
  phoneNumber: '',
  cardBalance: 0,
  paymentItems: []
});

// 当前选中的患者ID
const currentPatientId = ref(1);

// 患者列表
const patientList = ref<Patient[]>([]);

// 患者选择弹窗
const showPatientSelector = ref(false);

// 加载数据
const loading = ref(false);

// 获取所有患者
const fetchPatients = async () => {
  try {
    const response = await axiosrmedical.get('/Patient/GetPatients');
    const responseData: PatientResponse = response.data;
    if (responseData.code === 200) {
      patientList.value = responseData.pageData || [];
      
      return patientList.value;
    }
    return [];
  } catch (error) {
    console.error('获取患者列表失败:', error);
   
    return patientList.value;
  }
};

// 获取缴费项目数据
const fetchPaymentItems = async (patientId: number = currentPatientId.value) => {
  loading.value = true;
  try {
    const response = await axiosrmedical.get('/Payment/GetPatientPaymentItems', {
      params: {
        patientId
      }
    });
    const responseData: ResponseData = response.data;
    if (responseData.code === 200) {
      patientData.value = responseData.data;
    }
  } catch (error) {
    console.error('获取缴费项目失败:', error);
  } finally {
    loading.value = false;
  }
};

// 打开患者选择器
const openPatientSelector = () => {
  fetchPatients();
  showPatientSelector.value = true;
};

// 选择患者
const selectPatient = (patient: Patient) => {
  currentPatientId.value = patient.id;
  showPatientSelector.value = false;
  
  // 更新患者信息
  patientData.value = {
    ...patientData.value,
    patientId: patient.id,
    patientName: patient.name,
    idCard: patient.idCard,
    relation: patient.relation,
    paymentItems: [] // 清空原有缴费项目
  };
  
  // 获取新选择患者的缴费项目
  fetchPaymentItems(patient.id);
};

// 去缴费
const handlePayment = (item: PaymentItem) => {
  console.log('缴费项目:', item);
  // 跳转到缴费详情页
  router.push({
    path: '/payment-detail',
    query: {
      paymentId: String(item.id)
    }
  });
};

// 格式化时间
const formatDate = (dateString: string) => {
  const date = new Date(dateString);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
};

// 页面加载时获取数据
onMounted(() => {
  // 初始化获取缴费项目
  fetchPaymentItems();
  
  // 同时获取患者列表，并设置默认患者
  fetchPatients().then(() => {
    if (patientList.value && patientList.value.length > 0) {
      const defaultPatient = patientList.value.find(p => p.relation === '本人') || patientList.value[0];
      patientData.value.relation = defaultPatient.relation;
    }
  });
});
</script>

<template>
  <div class="payment-page">
    <!-- 顶部导航栏 -->
    <van-nav-bar 
      title="自助缴费" 
      left-arrow
      @click-left="$router.back()"
    >
      <template #right>
        <van-icon name="ellipsis" size="20" />
        <van-icon name="circle" size="20" class="ml-2" />
      </template>
    </van-nav-bar>

    <!-- 用户信息卡片 -->
    <div class="user-card">
      <div class="user-info" @click="openPatientSelector">
        <span class="user-name">{{ patientData.patientName}}</span>
        <div class="patient-type">
          <span class="user-type">{{ patientData.relation || '本人' }}</span>
        <van-icon name="arrow" class="switch-user-icon" />
        </div>
      </div>
      <div class="user-id">{{ patientData.idCard }}</div>
    </div>

    <!-- 卡内余额 -->
    <div class="balance-card">
      <div class="balance-label">卡内余额</div>
      <div class="balance-amount">¥{{ patientData.cardBalance || '60.00' }}</div>
    </div>

    <!-- 待缴费项目 -->
    <div class="payment-section">
      <div class="section-title">待缴费项目</div>
      
      <van-list v-if="patientData.paymentItems && patientData.paymentItems.length > 0">
        <div 
          class="payment-item" 
          v-for="item in patientData.paymentItems" 
          :key="item.id"
        >
          <div class="item-content">
            <div class="item-name">{{ item.itemName }}</div>
            <div class="item-amount">¥{{ item.amount.toFixed(2) }}</div>
          </div>
          <div class="item-detail">
            <span>{{ item.departmentName }} {{ item.doctorName }}</span>
            <span>{{ formatDate(item.createdTime) }}</span>
          </div>
          <div class="item-action">
            <van-button 
              type="primary" 
              size="small" 
              round 
              class="pay-button"
              @click="handlePayment(item)"
            >
              去缴费
            </van-button>
          </div>
        </div>
      </van-list>

      <!-- 无数据时显示模拟数据 -->
      <div v-if="!patientData.paymentItems || patientData.paymentItems.length === 0">
        <div class="payment-item">
          <div class="item-content">
            <div class="item-name">西药费</div>
            <div class="item-amount">¥60.00</div>
          </div>
          <div class="item-detail">
            <span>神经内科 刘美</span>
            <span>2020-06-15 11:05</span>
          </div>
          <div class="item-action">
            <van-button 
              type="primary" 
              size="small" 
              round 
              class="pay-button"
              @click="router.push('/payment-detail?paymentId=1')"
            >
              去缴费
            </van-button>
          </div>
        </div>
        
        <div class="payment-item">
          <div class="item-content">
            <div class="item-name">检验费</div>
            <div class="item-amount">¥60.00</div>
          </div>
          <div class="item-detail">
            <span>神经内科 刘美</span>
            <span>2020-06-15 11:05</span>
          </div>
          <div class="item-action">
            <van-button 
              type="primary" 
              size="small" 
              round 
              class="pay-button"
              @click="router.push('/payment-detail?paymentId=2')"
            >
              去缴费
            </van-button>
          </div>
        </div>
        
        <div class="payment-item">
          <div class="item-content">
            <div class="item-name">检查费</div>
            <div class="item-amount">¥60.00</div>
          </div>
          <div class="item-detail">
            <span>神经内科 刘美</span>
            <span>2020-06-15 11:05</span>
          </div>
          <div class="item-action">
            <van-button 
              type="primary" 
              size="small" 
              round 
              class="pay-button"
              @click="router.push('/payment-detail?paymentId=3')"
            >
              去缴费
            </van-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 加载中提示 -->
    <van-loading v-if="loading" class="loading-spinner" />
    
    <!-- 患者选择弹窗 -->
    <van-popup
      v-model:show="showPatientSelector"
      position="center"
      round
      closeable
      :style="{ width: '85%', maxHeight: '70%' }"
    >
      <div class="patient-selector">
        <div class="selector-title">选择就诊人</div>
        <div class="patient-list">
          <div 
            v-for="patient in patientList" 
            :key="patient.id"
            class="patient-item"
            @click="selectPatient(patient)"
          >
            <div class="patient-info">
              <span class="patient-name">{{ patient.name }}</span>
              <span class="patient-relation" :class="{ 'relation-self': patient.relation === '本人' }">{{ patient.relation }}</span>
            </div>
            <div class="patient-id">{{ patient.idCard }}</div>
            <van-icon name="arrow" class="arrow-icon" />
          </div>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<style scoped>
.payment-page {
  height: 100vh;
  background-color: #f5f7fa;
  display: flex;
  flex-direction: column;
}

.user-card {
  background-color: #ffffff;
  padding: 16px;
  margin-bottom: 1px;
}

.user-info {
  display: flex;
  align-items: center;
  margin-bottom: 4px;
}

.user-name {
  font-size: 16px;
  font-weight: 500;
  margin-right: 8px;
}

.user-type {
  font-size: 14px;
  color: #0066ff;
  margin-right: 4px;
}

.switch-user-icon {
  color: #999;
}

.user-id {
  font-size: 14px;
  color: #999;
}

.balance-card {
  background-color: #ffffff;
  padding: 16px;
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.balance-label {
  font-size: 14px;
  color: #333;
}

.balance-amount {
  font-size: 16px;
  font-weight: 600;
}

.payment-section {
  flex: 1;
  background-color: #ffffff;
  padding: 0 16px;
}

.section-title {
  font-size: 15px;
  color: #333;
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
}

.payment-item {
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
}

.item-content {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.item-name {
  font-size: 15px;
  font-weight: 500;
}

.item-amount {
  font-size: 15px;
  font-weight: 600;
  color: #ff4d4f;
}

.item-detail {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #999;
  margin-bottom: 12px;
}

.item-action {
  display: flex;
  justify-content: flex-end;
}

.pay-button {
  width: 80px;
  height: 32px;
}

.loading-spinner {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.ml-2 {
  margin-left: 8px;
}

/* 患者选择相关样式 */
.patient-type {
  display: flex;
  align-items: center;
}

.patient-selector {
  padding: 16px;
}

.selector-title {
  text-align: center;
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f5f5f5;
}

.patient-list {
  max-height: 400px;
  overflow-y: auto;
}

.patient-item {
  padding: 15px 0;
  border-bottom: 1px solid #f5f5f5;
  position: relative;
  cursor: pointer;
  display: flex;
  flex-direction: column;
}

.patient-info {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
}

.patient-name {
  font-size: 16px;
  font-weight: 500;
  margin-right: 10px;
}

.patient-relation {
  font-size: 12px;
  color: #999;
  padding: 2px 8px;
  background-color: #f5f5f5;
  border-radius: 10px;
}

.relation-self {
  color: #0066ff;
  background-color: #e6f0ff;
}

.patient-id {
  font-size: 14px;
  color: #999;
}

.arrow-icon {
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  color: #ccc;
  font-size: 16px;
}
</style> 